package session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 读取Session
 */
public class S2_ReadSession extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("S2_ReadSession被调用...");

        //1.读取session，如果没有session，也会创建
        HttpSession session = req.getSession();
        System.out.println("读取到的sessionId=" + session.getId());
        //2.读取属性
        Object obj = session.getAttribute("email");
        if (obj != null) {
            System.out.println("session属性 email=" + (String) obj);
        } else {
            System.out.println("session中没有email属性...");
        }

        //3.回送浏览器
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>读取session成功~</h1>");
        writer.flush();
        writer.close();
    }
}
